package com.lids.test;

import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

/**
 * @Des
 * @Date: 2021/1/11 16:41
 */
public class LoginAuthReqHandler extends ChannelHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
         ctx.writeAndFlush(buildLoginReq());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
         NettyMessage message = (NettyMessage)msg;
         System.out.println("------------------------------------");
         //如果是握手应答消息，需判断是否认证成功
         if(message.getHeader()!= null && message.getHeader().getType() == MessageType.LOGIN_RESP.value()){
             byte loginResult = (byte)message.getBody();
             if(loginResult != (byte)0){
                 ctx.close();
             }else {
                 System.out.println("Login is Ok:"+message);
             }
         }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("------------------------------------");
        ctx.fireExceptionCaught(cause);
    }

    private Object buildLoginReq() {
        NettyMessage message = new NettyMessage();
        Header header = new Header();
        header.setType(MessageType.LOGIN_REQ.value());
        message.setHeader(header);
        return message;
    }
}
